package cn.lcsjsxy.yxc.multithreading.synchronization;

/**
 * 使用同步方法解决实现继承Thread的线程安全问题
 *
 * 关于同步方法的总结
 * 1.同步方法仍然涉及到同步监视器，只是不需要我们显式的声明
 * 2.非静态的同步方法，同步监视器式：this
 *   静态的同步方法，同步监视器是：当前类本身
 */
class Window2 extends Thread {
    private static int TICKET = 100;
    static Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            show();
            if (TICKET<=0)
                break;
        }
    }

    private static synchronized void show() {  //同步监视器
        if (TICKET > 0) {
            System.out.println(Thread.currentThread().getName() + ":卖票，票号为：" + TICKET);
            TICKET--;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class WindowThreadSynchronizationTest {
    public static void main(String[] args) {
        Window2 windowOne = new Window2();
        Window2 windowTwo = new Window2();
        Window2 windowThree = new Window2();
        windowOne.start();
        windowTwo.start();
        windowThree.start();
    }
}
